package com.example.sharesinfo.fragment;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;


import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;


import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.example.sharesinfo.R;
import com.example.sharesinfo.adapter.CommonAdapter;
import com.example.sharesinfo.adapter.CommonViewHolder;
import com.example.sharesinfo.base.BaseFragment;
import com.example.sharesinfo.bean.PersonalCenterBean;
import com.example.sharesinfo.bean.TalkBean;
import com.example.sharesinfo.entity.Constants;
import com.example.sharesinfo.helper.UIHelper;
import com.example.sharesinfo.model.CommentModel;
import com.example.sharesinfo.model.TalkModel;
import com.example.sharesinfo.ui.ImagePreviewActivity;
import com.example.sharesinfo.ui.NewsInfoActivity;
import com.example.sharesinfo.ui.PersonalCenterActivity;
import com.example.sharesinfo.ui.PushSquareActivity;
import com.example.sharesinfo.utils.LogUtils;
import com.example.sharesinfo.utils.OkHttpUtils;
import com.example.sharesinfo.utils.SpUtils;
import com.example.sharesinfo.view.InputTextMsgDialog;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class CommunityFragment extends BaseFragment implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
    private CommunityFragment fa;
    private static final int REQUEST_CODE = 1000;
    private static final String LOGTAG = "CommunityFragment:";
    private ImageView iv_push;
    private RecyclerView mTalkView;
    private SwipeRefreshLayout mTalkSwipeLayout;
    private View item_empty_view;
    private boolean isFlag = false;
    private static final int QUERY_USER_CODE = 1001;
    //悬浮按钮
    private FloatingActionButton fb_squaue_top;

    //
    private List<TalkModel> mList = new ArrayList<>();
    private CommonAdapter<TalkModel> mTalkAdapter;

    //TalkId=***&UserId=***
    private String SendTalkPraiseUrl = "http://119.23.221.142/api/talk/SendTalkPraise?";
    private Map<String, String> praiseDatas = new HashMap<>();
    //TalkId=***&UserId=***
    private String CancelTalkPraiseURl = "http://119.23.221.142/api/talk/CancelTalkPraise?";
    private Map<String, String> CancelPraiseDatas = new HashMap<>();
    //


    public CommunityFragment getFragment() {
        if (fa == null) {
            fa = new CommunityFragment();
        }
        return fa;
    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 200:
                    if (mList.size() > 0) {
                        mList.clear();
                    }
                    TalkBean result = (TalkBean) msg.obj;
                    LogUtils.i("说说评论：" + result.getData().get(0).getCommentData().get(0).getPoint());
                    for (int i = 0; i < result.getData().size(); i++) {
                        TalkModel model = new TalkModel();
                        model.setId(result.getData().get(i).getId());
                        model.setImageUrl(result.getData().get(i).getImageUrl());
                        model.setUserId(result.getData().get(i).getUserId());
                        model.setUsername(result.getData().get(i).getUsername());
                        model.setStockAge(result.getData().get(i).getStockAge());
                        model.setTalkTime(result.getData().get(i).getTalkTime());
                        model.setContent(result.getData().get(i).getContent());
                        model.setPictureUrl(result.getData().get(i).getPictureUrl());
                        model.setReadNumber(result.getData().get(i).getReadNumber());
                        model.setPraiseNumber(result.getData().get(i).getPraiseNumber());
                        model.setCommentNumber(result.getData().get(i).getCommentNumber());
                        model.setIf_Praise(result.getData().get(i).getIf_Praise());
                        model.setCommentData(result.getData().get(i).getCommentData());
                        mList.add(model);
                    }
                    mTalkAdapter.notifyDataSetChanged();
                    UIHelper.hideDialogForLoading();
                    mTalkSwipeLayout.setRefreshing(false);
                    break;
                case QUERY_USER_CODE:
                    PersonalCenterBean result1 = (PersonalCenterBean) msg.obj;
                    PersonalCenterActivity.startActivity(getContext(), result1, false);
                    break;
                case 404:

                    break;
            }


            return false;
        }
    });

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_community, null);
        UIHelper.showDialogForLoading(getContext(), "加载中...");
        initView(view);
        queryDatas();
        return view;
    }

    private void queryDatas() {

        String url = "http://119.23.221.142/api/talk/GetTalkList?UserId="
                + SpUtils.getInstance().getString(Constants.SP_USER_ID, "");
        LogUtils.i(LOGTAG + url);
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {

                TalkBean bean = new Gson().fromJson(s, TalkBean.class);
                message.what = code;
                message.obj = bean;
                mHandler.sendMessage(message);
            }

            @Override
            public void OnFailed(String s) {
                message.what = 404;
                message.obj = s;
                mHandler.sendMessage(message);
            }
        });

    }


    private void initView(final View view) {
        isFlag = false;
        iv_push = view.findViewById(R.id.iv_push);
        mTalkView = view.findViewById(R.id.mTalkView);
        mTalkSwipeLayout = view.findViewById(R.id.mTalkSwipeLayout);
        item_empty_view = view.findViewById(R.id.item_empty_view);
        fb_squaue_top = view.findViewById(R.id.fb_squaue_top);

        iv_push.setOnClickListener(this);
        fb_squaue_top.setOnClickListener(this);
        mTalkSwipeLayout.setOnRefreshListener(this);


        mTalkView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mTalkView.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.VERTICAL));
        //取消动画
        ((SimpleItemAnimator) mTalkView.getItemAnimator()).setSupportsChangeAnimations(false);
        mTalkAdapter = new CommonAdapter<>(mList, new CommonAdapter.OnMoreBindDataListener<TalkModel>() {
            @Override
            public int getItemType(int position) {
                return position;
            }

            @Override
            public void onBindViewHolder(final TalkModel model, final CommonViewHolder viewHolder, int type, final int position) {
                final ImageView praised = viewHolder.getView(R.id.iv_praised);
                if (praiseDatas.size() > 0) {
                    praiseDatas.clear();
                }
                if (CancelPraiseDatas.size() > 0) {
                    CancelPraiseDatas.clear();
                }
                if (!model.getIf_Praise().equals("False")) {
                    praised.setImageResource(R.drawable.praise_checked);
                    praised.setTag("checked");
                } else {
                    praised.setImageResource(R.drawable.praise_unchecked);
                    praised.setTag("unchecked");
                }
                final int[] praise = {Integer.parseInt(model.getPraiseNumber())};
                praised.setOnClickListener(new View.OnClickListener() {
                    //点赞事件
                    @Override
                    public void onClick(View v) {
                        if (praised.getTag().equals("unchecked")) {
                            praised.setImageResource(R.drawable.praise_checked);
                            praise[0] += 1;
                            viewHolder.setText(R.id.tv_praise_number, "" + praise[0]);
                            praised.setTag("checked");
                            //TalkId=***&UserId=***
                            praiseDatas.put("TalkId", String.valueOf(model.getId()));
                            praiseDatas.put("UserId", SpUtils.getInstance().getString(Constants.SP_USER_ID, ""));
                            OkHttpUtils.getInstance().Post(SendTalkPraiseUrl, null,
                                    praiseDatas, null, null,
                                    new OkHttpUtils.okHttpListener() {
                                        @Override
                                        public void OnSuccess(String s, int code) throws JSONException {
                                            LogUtils.i("点赞事件处理" + "点赞成功" + s);
                                        }

                                        @Override
                                        public void OnFailed(String s) {
                                            LogUtils.i("点赞事件处理" + "点赞失败");
                                        }
                                    });
                        } else if (praised.getTag().equals("checked")) {
                            LogUtils.i("点赞事件处理" + "取消点赞");
                            praised.setImageResource(R.drawable.praise_unchecked);
                            praise[0] -= 1;
                            viewHolder.setText(R.id.tv_praise_number, "" + praise[0]);
                            praised.setTag("unchecked");
                            //TalkId=***&UserId=***
                            CancelPraiseDatas.put("TalkId", String.valueOf(model.getId()));
                            CancelPraiseDatas.put("UserId", SpUtils.getInstance().getString(Constants.SP_USER_ID, ""));
                            OkHttpUtils.getInstance().Post(CancelTalkPraiseURl, null,
                                    CancelPraiseDatas, null, null, new OkHttpUtils.okHttpListener() {
                                        @Override
                                        public void OnSuccess(String s, int code) throws JSONException {
                                            LogUtils.i("点赞事件处理" + "取消点赞成功" + s);
                                        }

                                        @Override
                                        public void OnFailed(String s) {
                                            LogUtils.i("点赞事件处理" + "取消点赞失败");
                                        }
                                    });

                        }
                    }
                });

                viewHolder.setImageUrl(getContext(), R.id.ci_photo, model.getImageUrl());
                viewHolder.setText(R.id.tv_username, model.getUsername());
                viewHolder.setText(R.id.tv_stockAge, "股龄" + model.getStockAge());
                viewHolder.setText(R.id.tv_time, model.getTalkTime());
                viewHolder.setText(R.id.iv_read_number, "浏览" + model.getReadNumber() + "次");
                viewHolder.setText(R.id.tv_praise_number, model.getPraiseNumber());
                viewHolder.setText(R.id.tv_comment_number, model.getCommentNumber());
                viewHolder.setText(R.id.tv_content, model.getContent());
                //判断是否含有图片的说说
                if (model.getPictureUrl() == null) {
                    viewHolder.getView(R.id.iv_img).setVisibility(View.GONE);
                } else {
                    viewHolder.getView(R.id.iv_img).setVisibility(View.VISIBLE);
                    viewHolder.setImageUrl(getContext(), R.id.iv_img, model.getPictureUrl());
                    viewHolder.getView(R.id.iv_img).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ImagePreviewActivity.startActivity(
                                    getContext(), true, model.getPictureUrl());
                        }
                    });
                }
                viewHolder.getView(R.id.ci_photo).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        queryUserInfo(model.getUserId());

                    }
                });
                //说说评论
                RecyclerView rc_call_back = viewHolder.getView(R.id.rc_call_back);
                rc_call_back.setLayoutManager(new LinearLayoutManager(getActivity()));
                final List<CommentModel> list = new ArrayList<>();
                list.addAll(model.getCommentData());
                LogUtils.i(LOGTAG + list.size());
                final CommonAdapter<CommentModel> mCommonAdapter = new CommonAdapter<>(list, new CommonAdapter.OnBindDataListener<CommentModel>() {
                    @Override
                    public void onBindViewHolder(CommentModel model, CommonViewHolder viewHolder, int type, int position) {
                        viewHolder.setText(R.id.tv_username, model.getUsername());
                        viewHolder.setText(R.id.tv_content, model.getPoint());
                    }

                    @Override
                    public int getLayoutId(int type) {
                        return R.layout.layout_call_back_item;
                    }
                });
                rc_call_back.setAdapter(mCommonAdapter);
                //发表评论add_comment
                TextView tvAdd = viewHolder.getView(R.id.add_comment);
                final InputTextMsgDialog inputTextMsgDialog;
                inputTextMsgDialog = new InputTextMsgDialog(getContext(), R.style.customdialogstyle);
                inputTextMsgDialog.setmOnTextSendListener(new InputTextMsgDialog.OnTextSendListener() {
                    @Override
                    public void onTextSend(String msg) {
                        LogUtils.i(LOGTAG + msg + "postion" + position);
                        CommentModel model1 = new CommentModel();
                        model1.setUserId(SpUtils.getInstance().getString(Constants.SP_USER_ID, ""));
                        model1.setPoint(msg);
                        model1.setUsername(SpUtils.getInstance().getString(Constants.SP_USER_NAME, ""));
                        list.add(model1);
                        LogUtils.i(LOGTAG + list.size());
                        mCommonAdapter.notifyDataSetChanged();
                        SendComment(String.valueOf(model.getId()), msg);
                        Toast.makeText(getContext(), "评论成功", Toast.LENGTH_SHORT).show();
                    }
                });

                tvAdd.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        inputTextMsgDialog.show();
                    }
                });

            }

            @Override
            public int getLayoutId(int type) {
                return R.layout.community_list_item;
            }
        });
        mTalkView.setAdapter(mTalkAdapter);
        //监听列表滑动
        mTalkView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @SuppressLint("RestrictedApi")
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                if (layoutManager != null) {
                    if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
                        int position = ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition();
                        if (position > 4) {
                            fb_squaue_top.setVisibility(View.VISIBLE);
                        } else {
                            fb_squaue_top.setVisibility(View.GONE);
                        }
                    }
                }
            }
        });
    }

    private void queryUserInfo(int userId) {
        String url = "http://119.23.221.142/api/user/GetHomePage?UserId=" + userId
                + "&MyId=" + SpUtils.getInstance().getString(Constants.SP_USER_ID, "");
        LogUtils.i(url);
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                LogUtils.i(LOGTAG + s);
                PersonalCenterBean bean = new Gson().fromJson(s, PersonalCenterBean.class);
                message.what = QUERY_USER_CODE;
                message.obj = bean;
                mHandler.sendMessage(message);
            }

            @Override
            public void OnFailed(String s) {
                message.what = 404;
                message.obj = s;
                mHandler.sendMessage(message);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CODE) {
                //刷新
                LogUtils.i(LOGTAG + "返回刷新");
                mTalkSwipeLayout.setRefreshing(true);
                queryDatas();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_push:
                Intent intent = new Intent(getActivity(), PushSquareActivity.class);
                startActivityForResult(intent, REQUEST_CODE);
                break;
            case R.id.fb_squaue_top:
                mTalkView.smoothScrollToPosition(0);
                break;
        }
    }

    public void SendComment(String TalkId, String Point) {
        String urlRoot = "http://119.23.221.142/api/talk/SendComment?";
        Map<String, String> datas = new HashMap<>();
        datas.put("UserId", SpUtils.getInstance().getString(Constants.SP_USER_ID, ""));
        datas.put("TalkId", TalkId);
        datas.put("Point", Point);
        OkHttpUtils.getInstance().Post(urlRoot, null, datas,
                null, null, new OkHttpUtils.okHttpListener() {
                    @Override
                    public void OnSuccess(String s, int code) throws JSONException {
                        LogUtils.i(LOGTAG + s);
                    }

                    @Override
                    public void OnFailed(String s) {

                    }
                });

    }

    @Override
    public void onRefresh() {
        mTalkSwipeLayout.setRefreshing(true);
        queryDatas();
    }


}
